/*
 *   Time Tracking Web Application
 *   Copyright (C) 2008, Nick Griffiths
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *   
 *   Contact nicobrevin at gmail dot com
 *   http://code.google.com/p/openharvest/
 */

package org.brevs.time.dao;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.appfuse.model.User;
import org.brevs.time.model.Entry;
import org.brevs.time.model.Project;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class TimeDaoHibernate extends HibernateDaoSupport implements TimeDao {
	
	public void saveEntry(Entry entry) {
		getHibernateTemplate().saveOrUpdate(entry);
	}

	public List<Entry> getEntries(User user, Date day) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(day);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		Date startDate = cal.getTime();
		cal.add(Calendar.DATE, 1);
		Date endDate = cal.getTime();
		
		StringBuilder builder = new StringBuilder();
		builder.append("select e from ").append(Entry.class.getName()).append(" e");
		builder.append(" where e.user.id = ? and (e.startDate >= ? and e.startDate < ?)");
		
		return getHibernateTemplate().find(builder.toString(), new Object[] {user.getId(), startDate, endDate});
	}
	
	@SuppressWarnings("unchecked")
	public List<Entry> getEntries(User user, boolean running) {
		StringBuilder builder = new StringBuilder();
		builder.append("select e from ").append(Entry.class.getName()).append(" e");
		builder.append(" where e.user.id = ? and e.startedRunning is ");
		if (running) {
			builder.append(" not ");
		}
		builder.append("null");
		
		return getHibernateTemplate().find(builder.toString(), new Object[] {user.getId()});
	}
	
	public List<Project> getProjects() {
		return getHibernateTemplate().loadAll(Project.class);
	}
	
	public void saveProject(Project project) {
		getHibernateTemplate().saveOrUpdate(project);
	}

	public Entry getEntry(Long id) {
		return (Entry) getHibernateTemplate().get(Entry.class, id);
	}
}
